package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 文件上传的通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    private final AliOssUtil aliOssUtil;

    public CommonController(AliOssUtil aliOssUtil) {
        this.aliOssUtil = aliOssUtil;
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {

        log.info(file.getName());

        //获取原始文件名称
        String originalFilename = file.getOriginalFilename();
        String subfileName = originalFilename.substring(originalFilename.lastIndexOf("."));

        //将文件上传到阿里云
        String finleName = UUID.randomUUID().toString() + subfileName;

        try {
            String upload = aliOssUtil.upload(file.getBytes(), finleName);
            return Result.success(upload);
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);

    }

}
